package com.now.printer.utils;

import android.content.Context;
import android.os.Handler;
import android.os.Message;

import com.now.printer.base.MyApplication;
import com.now.printer.db.DocumentsTable;

import org.xutils.DbManager;
import org.xutils.common.util.LogUtil;
import org.xutils.ex.DbException;
import org.xutils.x;

import java.util.List;

public class DbUtils {

    public static final DbManager.DaoConfig daoConfig = new DbManager.DaoConfig()
            .setDbName("documents.db")
            // 不设置dbDir时, 默认存储在app的私有目录.
            //new File("/sdcard")
            .setDbDir(MyApplication.getMyAppContext().getExternalFilesDir(null)) // "sdcard"的写法并非最佳实践, 这里为了简单, 先这样写了.
            .setDbVersion(2)
            .setDbOpenListener(new DbManager.DbOpenListener() {
                @Override
                public void onDbOpened(DbManager db) {
                    // 开启WAL, 对写入加速提升巨大
                    db.getDatabase().enableWriteAheadLogging();
                }
            })
            .setDbUpgradeListener(new DbManager.DbUpgradeListener() {
                @Override
                public void onUpgrade(DbManager db, int oldVersion, int newVersion) {
                    // TODO: ...
                    // db.addColumn(...);
                    // db.dropTable(...);
                    // ...
                    // or
                    // db.dropDb();
                }
            });

    public static void initSystemFileDb(Context context, Handler handler){
            x.task().run(() -> {
                List<DocumentsTable> systemFileLists = FileManager.getInstance(context).getAllFilesList();
                LogUtil.i("查找系统级文件库的文件数：" + systemFileLists.size());

                try {
                    DbManager db = x.getDb(DbUtils.daoConfig);
                    List<DocumentsTable> documentsTableList = db.selector(DocumentsTable.class).findAll();

                    if (documentsTableList != null) {
                        LogUtil.i("自定义存储数据库文件数：" + documentsTableList.size());

                        if (documentsTableList.size() !=  systemFileLists.size()) {
                            db.delete(DocumentsTable.class);
                            db.save(systemFileLists);
                        }
                    }else {
                        db.save(systemFileLists);
                    }

                    if (handler != null){
                        Message msg = new Message();
                        msg.obj = systemFileLists;
                        msg.what = 1;
                        handler.sendMessageDelayed(msg,0);
                    }

                } catch (DbException ex) {
                    ex.printStackTrace();
                    LogUtil.e("DbException" + ex.getLocalizedMessage());
                }
            });

    }

}
